<template>
  <div class="container">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import Neo4jAPI, { Disease } from "@/api/neo4j/diseases";
import * as echarts from "echarts";
const chartRef = ref<HTMLElement | null>(null);
const chartInstance = ref<echarts.ECharts | null>(null);

// 渲染图表
const renderChart = (data: Disease[]) => {
  if (!chartRef.value) {
    console.error("Chart container is not initialized.");
    return;
  }

  // 如果 ECharts 实例不存在，则初始化
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartRef.value);
  } else {
    // 清除旧的数据和配置
    chartInstance.value.clear();
  }

  // 处理节点和关系
  const nodes = data.flatMap((disease) => [
    {
      id: `disease-${disease.id}`, // 使用疾病ID作为唯一标识
      name: disease.name,
      category: "Disease",
      symbolSize: 60,
      itemStyle: {
        color: "red", // 疾病节点背景色为红色
      },
      label: {
        show: true,
        color: "white", // 疾病节点文字颜色为白色
        fontSize: 14,
      },
    },
    ...disease.drugs.map((drug) => ({
      id: `drug-${drug.drug.name}`, // 使用药品名称作为唯一标识
      name: drug.drug.name,
      category: "Drug",
      symbolSize: 60, // 设置节点大小
      label: {
        show: true,
        color: "black", // 药品节点文字颜色为白色
        fontSize: 12,
      },
    })),
  ]);

  // 去重：确保节点ID唯一
  const nodeMap = new Map();
  nodes.forEach((node) => {
    if (!nodeMap.has(node.id)) {
      nodeMap.set(node.id, node);
    }
  });
  const uniqueNodes = Array.from(nodeMap.values());

  // 处理关系
  const links = data.flatMap((disease) =>
    disease.drugs.map((drug) => ({
      source: `disease-${disease.id}`, // 使用疾病ID作为源节点
      target: `drug-${drug.drug.name}`, // 使用药品名称作为目标节点
      name: drug.type, // 关系类型
      label: {
        show: true, // 显示关系标签
        color: "#333", // 设置字体颜色
        fontSize: 12, // 设置字体大小
        //backgroundColor: "#fff", // 设置字体背景色
        //padding: [2, 4], // 设置内边距
        //borderRadius: 3, // 设置圆角
      },
    }))
  );

  const option = {
    title: {
      text: "知识图谱",
      subtext: "xxxx",
      top: "top",
      left: "left",
    },
    tooltip: {},
    legend: {
      data: ["Disease", "Drug"],
      // selectedMode: "multiple", // 允许点击图例隐藏/显示数据系列
    },
    animationDurationUpdate: 1500,

    series: [
      {
        type: "graph",
        //layout: "force",
        layout: "circular",
        symbolSize: 50,
        roam: true,
        data: uniqueNodes,
        links: links,
        categories: [{ name: "Disease" }, { name: "Drug" }],

        label: {
          normal: {
            show: true,
            color: "white", // 疾病节点文字颜色为白色
            textStyle: {},
          },
        },
        edgeSymbol: ["circle", "arrow"],
        edgeSymbolSize: [4, 10],
        edgeLabel: {
          fontSize: 12,
          show: true,
        },
        force: {
          repulsion: 1000, // 调整节点之间的斥力
          edgeLength: [50, 200], // 边的长度范围
          gravity: 0.1, // 引力系数
        },
        draggable: true,
      },
    ],
  };

  // 设置图表配置
  chartInstance.value.setOption(option);

  // 监听 Legend 点击事件  vue3 点击图标不能自动去掉连接线
  chartInstance.value.on("legendselectchanged", (params: any) => {
    const selected = params.selected;
    const updatedNodes = uniqueNodes.filter((node) => selected[node.category]);
    const updatedLinks = links.filter(
      (link) =>
        selected[uniqueNodes.find((node) => node.id === link.source)?.category] &&
        selected[uniqueNodes.find((node) => node.id === link.target)?.category]
    );

    // 更新图表
    chartInstance.value?.setOption({
      series: [
        {
          data: updatedNodes,
          links: updatedLinks,
        },
      ],
    });
  });
};

// 获取所有疾病
const fetchDiseases = async () => {
  const ids: number[] = [1, 2, 3];
  try {
    const data = await Neo4jAPI.getDiseasesByIds(ids);
    renderChart(data);
  } catch (error) {
    console.error("获取疾病列表失败:", error);
  }
};

onMounted(() => {
  fetchDiseases();
});
</script>

<style scoped>
.container {
  width: 100vw; /* 占满整个视口宽度 */
  height: 100vh; /* 占满整个视口高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart-container {
  width: 100%; /* 占满父容器宽度 */
  height: 100%; /* 占满父容器高度 */
}
</style>
